import { defineComponent, ref } from 'vue'
import { getPermissionData } from '@/api/permission'
import changeTreeData from '@/hooks/useChangeTree'
import { getRole, setRole } from '@/api/setting'
import { message } from 'ant-design-vue'

export default defineComponent({
  name: 'setPermission',
  setup(props, { expose }) {
    const visible = ref(false)
    const rolenData = ref({
      name: '',
      id: ''
    })
    const checkedKeys = ref([])
    const treeData = ref([])
    const handleOk = async () => {
      const res = (await setRole({
        id: rolenData.value.id,
        permIds: checkedKeys.value
      })) as any
      message.success(res.message)
      visible.value = false
    }
    const handlenAfterClose = () => {
      rolenData.value = {
        name: '',
        id: ''
      }
      checkedKeys.value = []
    }

    async function getPermission() {
      const res = (await getPermissionData()) as any
      treeData.value = changeTreeData(res.data, '0')
      console.log(treeData.value)
    }
    async function getRoleData(id: string) {
      const res = (await getRole(id)) as any
      checkedKeys.value = res.data.permIds
    }

    function handleVisible() {
      visible.value = true
    }
    ;(async function () {
      // 获取权限数据
      await getPermission()
    })()

    expose({
      rolenData,
      handleVisible,
      getRoleData
    })

    return () => (
      <>
        <a-modal
          v-model:visible={visible.value}
          title={'给' + rolenData.value.name + '添加权限'}
          onOk={handleOk}
          afterClose={handlenAfterClose}
        >
          <a-tree
            v-model:checkedKeys={checkedKeys.value}
            checkable
            tree-data={treeData.value}
            fieldNames={{
              title: 'name',
              key: 'id'
            }}
          />
        </a-modal>
      </>
    )
  }
})
